package cc.lucien.servlet;

import cc.lucien.service.LoginService;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    LoginService loginService = new LoginService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        HttpSession session = req.getSession();
        if (method == null){
            method = "login";
        }
        switch (method){
            case "login":
                resp.sendRedirect("login.jsp");
                session.setAttribute("err","");
                break;
            case "success":
                String username = req.getParameter("username");
                session.setMaxInactiveInterval(60);
                session.setAttribute("username", username);
                session.removeAttribute("err");
                if (username.equals("admin")){
                    resp.sendRedirect("user");
                    break;
                }
                resp.sendRedirect("index.jsp");
                break;
            default:
                session.setAttribute("err", method);
                resp.sendRedirect("login.jsp");
                break;
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String inCode = req.getParameter("inCode");
        String checkCode = (String) req.getSession().getServletContext().getAttribute("checkCode");
        String result = loginService.login(username, password, inCode, checkCode);
        resp.sendRedirect("login?method=" + result);
    }
}
